package com.hqb.multi_transfer.service;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

@Service
public class FileStorageService {

    private final Path uploadDir = Paths.get("uploads");

    public FileStorageService() throws IOException {
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }
    }

    public StoredFile store(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) return null;

        String original = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
        String ext = "";
        int idx = original.lastIndexOf('.');
        if (idx > 0) ext = original.substring(idx);

        String stored = UUID.randomUUID().toString() + ext;
        Path target = uploadDir.resolve(stored);
        Files.copy(file.getInputStream(), target);

        StoredFile sf = new StoredFile();
        sf.originalFilename = original;
        sf.storedFilename = stored;
        sf.contentType = file.getContentType();
        sf.size = file.getSize();
        return sf;
    }

    public Path load(String storedFilename) {
        if (storedFilename == null) return null;
        Path p = uploadDir.resolve(storedFilename);
        if (Files.exists(p)) return p;
        return null;
    }

    public static class StoredFile {
        public String originalFilename;
        public String storedFilename;
        public String contentType;
        public long size;
    }
}
